package org.karelun.rabbit.rcp.ui.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.cdo.net4j.CDONet4jSession;
import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration;
import org.eclipse.emf.cdo.net4j.CDONet4jUtil;
import org.eclipse.emf.cdo.view.CDOAdapterPolicy;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.karelun.rabbit.graph.GraphPackage;
import org.karelun.rabbit.rcp.editor.RabbitEditorInput;

public abstract class BaseTransactionHandler extends AbstractHandler{

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IConnector connector = Net4jUtil.getConnector(IPluginContainer.INSTANCE, "tcp", getHost());
		CDONet4jSessionConfiguration config = CDONet4jUtil.createNet4jSessionConfiguration();
		config.setConnector(connector);
		config.setRepositoryName(getRepositoryName());

		CDONet4jSession session = config.openNet4jSession();
		session.getPackageRegistry().putEPackage(GraphPackage.eINSTANCE);
		CDOView cdoView=openCDOView(session);
		cdoView.options().addChangeSubscriptionPolicy(CDOAdapterPolicy.ALL);
		
		openEditor(cdoView);
		return null;
	}

	protected String getHost(){
		return "localhost";
	}
	
	protected String getRepositoryName(){
		return "rabbit";
	}
	
	protected String getResourcePathName(){
		return "/rsd";
	}
	
	protected abstract CDOView openCDOView(CDONet4jSession session);
	
	protected abstract String getEditorId();
	
	private void openEditor(CDOView cdoView) {
		String resourcePathName=getResourcePathName();
		boolean hasResource=hasResource(cdoView,resourcePathName);
		if(!hasResource){
			MessageDialog.openInformation(null, "", "No resource path: "+resourcePathName);
			return;
		}
		IWorkbenchPage page =PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		String path = cdoView.getResource(resourcePathName).getPath();
		RabbitEditorInput editorInput = new RabbitEditorInput(cdoView, path);
		try {
			page.openEditor(editorInput, getEditorId());
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	protected abstract boolean hasResource(CDOView cdoView, String resourcePathName);
}
